<template>
  <a-modal :title="title"
           :visible="switch_"
           width="700px"
           height="500px"
           append-to-body
           :footer="null"
           @cancel="() => closeDialog(false)">
    <a-spin :spinning="spinning">
      <div class="el-dialog-content">
        <!-- 左边选中展示 -->
        <div class="content-left">
          <div class="top-tags">
            <div class="search-box">
              <a-input-search v-show="orgin.attrs.type == type"
                       v-model="searchText"
                       @search="searchData"
                       placeholder="搜索" />
              <div class="search-list" v-if="searchList.length > 0">
                <div class="list">
                  <div :title="item.name"
                       v-for="(item,index) in searchList"
                       :key="index"
                       @click="checkItem(item, $event)">
                    {{ item.name }}<span v-if="item.type == 2 && item.tag"> ({{ item.tag }})</span>
                    <div :title="item.belongs"
                         v-if="item.type == 2 && item.belongs"
                         class="benlongs">{{ item.belongs }}</div>
                  </div>
                </div>
              </div>
              <div class="search-list" v-if="showSearch">
                <div class="no-result">
                  没有匹配到任何结果
                </div>
              </div>
            </div>
            <!-- 左边选中展示taglists -->
            <TagListAntD :not-allowed="notAllowed"
                         v-model="tagLists"
                         :pro="pro"></TagListAntD>
          </div>
          <div class="bottom-button">
            <a-button type="primary"
                      @click="submit"
                      v-show="attrs.type == 'unit' && orgin.limit == 0">
              确定
            </a-button>
            <a-button type="primary"
                      @click="submit"
                      v-show="attrs.type == 'unit' && orgin.limit > 0">
              确定
            </a-button>
            <a-button type="primary"
                      @click="submit"
                      v-show="attrs.type == 'user' && orgin.limit == 0">
              确定
            </a-button>
            <a-button type="primary"
                      @click="submit"
                      v-show="attrs.type == 'user' && orgin.limit > 0">
              确定
            </a-button>
            <a-button class="button_wran"
                      @click="clearCheck">
              清空
            </a-button>
            <a-button @click="closeDialog">
              取消
            </a-button>
          </div>
        </div>
        <!-- 右边组织机构 -->
        <a-tabs v-if="slotTab && type == 'user'"
                default-active-key="1">
          <a-tab-pane key="1"
                      tab="组织架构">
            <div class="content-right">
              <!-- 导航标题 -->
              <div class="breadcrumb"
                   v-resize="DomResize">
                <a-breadcrumb>
                  <a-breadcrumb-item v-for="(breadcrumb, index) in breadcrumbLists"
                                     :key="breadcrumb">
                    <a @click="toLink(breadcrumb, index)">
                      {{ orgin.labelDataList[breadcrumb][pro.name] }}
                    </a>
                  </a-breadcrumb-item>
                </a-breadcrumb>
              </div>
              <!-- 数据列表 -->
              <div class="list-box"
                   :style="{ '--breadcrumbHeight': breadcrumbHeight }">
                <UserUnitListAntD ref="checkUserList"
                                  :type="attrs.type"
                                  :pro="pro"
                                  :breadcrumb-lists="breadcrumbLists"
                                  :not-allowed="notAllowed"></UserUnitListAntD>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane style="padding: 5px 10px;"
                      v-for="(name,key) in slotTab"
                      :key="key + 2"
                      :tab="name.name"
                      force-render>
            <slot :name="name.tab"
                  :tagLists="tagLists"></slot>
          </a-tab-pane>
        </a-tabs>
        <div v-else
             class="content-right">
          <!-- 导航标题 -->
          <div class="breadcrumb"
               v-resize="DomResize">
            <a-breadcrumb>
              <a-breadcrumb-item v-for="(breadcrumb, index) in breadcrumbLists"
                                 :key="breadcrumb">
                <a @click="toLink(breadcrumb, index)">
                  {{ orgin.labelDataList[breadcrumb][pro.name] }}
                </a>
              </a-breadcrumb-item>
            </a-breadcrumb>
          </div>
          <!-- 数据列表 -->
          <div class="list-box"
               :style="{ '--breadcrumbHeight': breadcrumbHeight }">
            <UserUnitListAntD ref="checkUserList"
                              :type="attrs.type"
                              :pro="pro"
                              :breadcrumb-lists="breadcrumbLists"
                              :not-allowed="notAllowed"></UserUnitListAntD>
          </div>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
const cloneDeep = require('clone')
import { message } from 'ant-design-vue'
import TagListAntD from './TagListAntD.vue'
import UserUnitListAntD from './UserUnitListAntD.vue'
import { getTreeUnitLisByNameOrCode, getTreeUserListByUnitIds, getTreeUserListByName } from './../../api/select'

const deepClone = require('clone')
export default {
  name: 'DialogAntD',
  provide () {
    return {
      dialog: this
    }
  },
  components: {
    TagListAntD,
    UserUnitListAntD
  },
  // 导入祖父级定义的名称
  inject: ['orgin'],
  props: {
    // 弹出框参数
    attrs: {
      type: Object,
      default: () => {
        return {}
      }
    },
    slotTab: {
      type: Array,
      default: null
    },
    pro: {
      type: Object,
      default: () => {
        return {}
      }
    },
    notAllowed: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'unit'
    }
  },
  data () {
    return {
      // 弹出框开关
      switch_: false,
      // 导航数据
      breadcrumbLists: [],
      tagLists: [],
      // 查询内容
      searchText: '',
      // 查询数据
      searchList: [],
      // 面包屑高度
      breadcrumbHeight: '50px',
      // 人员是否加载完成
      // userListLoading: false,
      checkedItems: [],
      spinning: false,
      showSearch:false
    }
  },
  watch: {
    dataList: {
      handler (val) { }
    },
    searchText:{
      handler (val) {
        this.showSearch = false
      },
      deep: true,
      immediate: true
    },
    slotTab: {
      handler (slotTab) {
        if (slotTab) {
          let arr = []
          slotTab.map(item => {
            arr = [...arr, ...item.data]
          })
          arr.map(item => {
            this.tagLists.push(item.id)
            this.tagLists = [...new Set(this.tagLists)]
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    title () {
      if (this.orgin.limit > 1) {
        return `${this.attrs.title}（${this.tagLists.length}/${this.orgin.limit}）`
      }
      return this.attrs.title
    },
    userNum () {
      let num = 0
      if (this.tagLists) {
        this.tagLists.forEach((item) => {
          if (
            this.orgin.labelDataList[item] &&
            this.orgin.labelDataList[item].type == 1
          ) {
            num += this.orgin.labelDataList[item].personCount
          } else {
            ++num
          }
        })
      }
      return num
    }
  },
  methods: {
    openDialog () {
      this.switch_ = true
    },
    closeDialog () {
      this.switch_ = false
      // 清空下拉
      this.searchText = ''
      this.searchList = []
      // this.tagLists = [];
      // this.notAllowed = [];
    },
    // 跳转面包屑，加载对应的列表数据
    toLink (breadcrumb, index) {
      this.orgin.loadNode(breadcrumb, this.orgin.needUnitType)
      this.breadcrumbLists.splice(
        index + 1,
        this.breadcrumbLists.length - index
      )
    },
    // 传出数据
    submit () {
      // 清空下拉
      this.searchText = ''
      this.searchList = []
      // 选择部门
      if (this.attrs.type == 'unit') {
        this.orgin.newValue = this.tagLists
        this.orgin.$emit('input', this.orgin.newValue)
        this.orgin.emitValue()
        // if (this.orgin.newValue.length > 0) {
        this.orgin.getReverseData()
        // }
        this.switch_ = false
      } else {
        // 选择人员
        const userLists = []
        const unitLists = []
        // 遍历格式化人员ID，取出部门id
        this.tagLists.forEach((id) => {
          if (id.substring(0, 4) == this.orgin.userIdFlag) {
            unitLists.push(id.substring(4, id.length))
          } else {
            userLists.push(id)
          }
        })
        // 如果根据部门选择人员

        if (unitLists.length > 0) {
          // this.userListLoading = true
          this.getUserIdLists(unitLists).then((res) => {
            // 合并去重
            this.tagLists = [...new Set(userLists.concat(res))]
            this.orgin.newValue = deepClone(this.tagLists)
            // 获取选中人员的返现数据
            this.orgin.getReverseData().then(() => {
              this.orgin.$emit('input', this.orgin.newValue)
              // this.userListLoading = false
              this.switch_ = false
              this.orgin.emitValue()
            })
          })
        } else {
          this.orgin.newValue = deepClone(this.tagLists)
          this.orgin.$emit('input', this.orgin.newValue)
          this.orgin.getReverseData()
          this.switch_ = false
          this.orgin.emitValue()
        }
        this.$nextTick(() => {
          this.orgin.emitValue()
        })
      }
    },
    /** 数据搜索 */
    searchData: function () {
      this.searchList = []
      if (!this.searchText) {
        return
      }
      let type = true // true为汉字
      const re = /^[0-9a-zA-Z]*$/ // 判断字符串是否为数字和字母组合
      let regex = /^[\u4E00-\u9FA5]+$/ // 判断字符串是否为汉字
      if (re.test(this.searchText)) {
        type = false
      } else if (regex.test(this.searchText)) {
        type = true
      }
      if (!type && this.searchText.length < 1) {
        return
      }
      this.spinning = true
      this.type == 'user'
        ? getTreeUserListByName(this.searchText, this.orgin.cantianSelf, this.orgin.topUnitId,this.orgin.label,this.orgin.extend).then((data) => {
          this.response(data)
        })
        : getTreeUnitLisByNameOrCode(this.searchText,this.orgin.label,this.orgin.extend).then((data) => {
          this.response(data)
        })
    },
    response (data) {
      if(data && data.length > 0){
        this.showSearch = false
      }else{
        this.showSearch = true
      }
      if (data) {
        this.searchList = data
        let labelDataList = {}
        this.searchList.forEach((item) => {
          // 缓存数据
          labelDataList[item.id] = item
        })
        this.orgin.labelDataList = { ...this.orgin.labelDataList, ...labelDataList }
        this.spinning = false
      }
    },
    /** 根据部门ids,获取下方所有人员id
     * @param {*} ids
     * @return function
     */
    getUserIdLists (ids) {
      if (!ids || ids.length == 0) return
      return new Promise((resolve, reject) => {
        getTreeUserListByUnitIds(ids.join(',') || '').then((data) => {
          if (data) {
            const arr = data.map((item) => {
              return item.id
            })
            resolve(arr)
          } else {
          }
        })
      })
    },
    // 选中，并关闭弹出框
    checkItem (item) {
      this.searchText = ''
      this.searchList = []

      // 判断是否选择
      if (this.tagLists.indexOf(item.id) == -1) {
        let nowNum
        if (this.orgin.attrs.type == 'user') {
          // 已选中人数
          nowNum = this.userNum
        } else {
          // 当前选中部门数
          nowNum = this.tagLists.length
        }
        // 判断选择是否超过最大限制
        if (nowNum + 1 > this.orgin.limit && this.orgin.limit > 0) {
          if (this.orgin.limit > 1) {
            message.warning('选择超过限制！！！')
            // 单选
          } else if (this.orgin.limit == 1) {
            this.tagLists = []
            this.tagLists.push(item.id)
          }
        } else {
          this.tagLists.push(item.id)
        }
      } else {
        message.error('不能重复选择！')
      }
    },
    // 清空所有选中数据
    clearCheck () {
      if (this.slotTab) {
        this.slotTab.map(item => {
          item.data = []
        })
      }

      this.$refs.checkUserList.checkedItems = []

      const arr = this.tagLists.filter((num) => {
        return this.notAllowed.indexOf(num) !== -1
      })
      this.tagLists = arr
    },
    // 获取面包屑高度
    DomResize (data) {
      const { height } = data
      this.breadcrumbHeight = height
    }
  },
  directives: {
    resize: {
      // 指令的名称
      bind (el, binding) {
        // el为绑定的元素，binding为绑定给指令的对象
        let width = ''
        let height = ''
        function isReize () {
          const style = document.defaultView.getComputedStyle(el)
          if (width !== style.width || height !== style.height) {
            binding.value({ width: style.width, height: style.height }) // 关键(这传入的是函数,所以执行此函数)
          }
          width = style.width
          height = style.height
        }
        el.__vueSetInterval__ = setInterval(isReize, 300)
      },
      unbind (el) {
        clearInterval(el.__vueSetInterval__)
      }
    }
  }
}
</script>

<style lang="less" scoped>
// 重置dialog样式
::v-deep .ant-modal-content {
  border-radius: 0px;
  .ant-modal-header {
    border-bottom: none;
    .ant-modal-title {
      color: #999;
    }
  }
  .ant-modal-body {
    padding: 0px;
  }
  .ant-checkbox + span {
    padding-right: 8px;
    padding-left: 8px;
    justify-content: space-between;
    display: flex;
  }
}
.el-dialog-content {
  height: 480px;
  display: flex;
  & > div {
    flex: 1;
  }
  .content-left {
    box-sizing: border-box;
    border-right: 1px solid #eee;
    .top-tags {
      box-sizing: border-box;
      height: 420px;
      width: 100%;
      padding: 10px 0px 20px 20px;
      overflow-y: auto;
    }
    .bottom-button {
      margin: 10px 0 0 15px;
      .ant-btn {
        margin-left: 15px;
      }
      .button_wran {
        color: #e6a23c;
        background: #fdf6ec;
        border-color: #f5dab1;
        &:hover {
          background: #cf9236;
          border-color: #cf9236;
          color: #ffffff;
        }
      }
    }
  }
  .content-right {
    .breadcrumb {
      min-height: 50px;
      padding: 10px 20px;
      box-sizing: border-box;
    }
    .list-box {
      max-height: calc(480px - var(--breadcrumbHeight));
      // height: 100%;
      box-sizing: border-box;
      overflow-y: auto;
    }
  }
}
// 查询列表样式
.search-box {
  position: relative;
  margin-bottom: 3px;
  .search-list {
    top: 45px;
    position: absolute;
    background-color: #fff;
    z-index: 9999;
    width: 310px;
    min-height: 70px;
    max-height: 350px;
    overflow-y: auto;
    box-shadow: 0 0 5px #ddd;
    border-radius: 5px;
    .list {
      padding: 10px 0;
      .benlongs {
        font-size: var(--font-size-12);
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
      }
      & > div {
        padding: 6px 20px;
        line-height: 25px;
        border-bottom: 1px solid #eee;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
        cursor: pointer;
        &:hover {
          background-color: #f5f5f5;
        }
        i {
          display: inline-block;
          margin-right: 5px;
        }
      }
      & > div:last-child {
        border-bottom: none;
      }
      & > div:first-child {
        border-bottom: 1px solid #eee;
      }
    }
    .no-result {
      text-align: center;
      line-height: 70px;
      font-size: 18px;
      color: #999;
    }
  }
}
</style>
